<?php


namespace app\admin\model;


use think\Model;

class article extends Model
{
      public function profile(){
          return $this->hasOne('Cate','id','cateid');
      }
      public static function init(){
          article::event('before_insert',function($data){
              if($_FILES['thumb']['tmp_name']){  //判断有无上传文件
                $file = request()->file('thumb');  //获取上传文件
                if($file){
                    $info = $file->move($_SERVER['DOCUMENT_ROOT'].'\uploads','',true,false);  //移动到框架应用根目录/uploads/ 目录下
                    if($info){
//                        echo $info->getExtension();  //输出后缀
//                        echo $info->getFilename();  //输出文件名称
                        $data['thumb'] = '/uploads'.'/'.$info->getFilename();
                    }
                }

            }

          });
          article::event('before_update',function($data){
              if($_FILES['thumb']['tmp_name']){  //判断有无上传文件
                  $file = request()->file('thumb');  //获取上传文件
                  if($file){
                      $info = $file->move($_SERVER['DOCUMENT_ROOT'].'\uploads','',true,false);  //移动到框架应用根目录/uploads/ 目录下

                      if($info){
//                        echo $info->getExtension();  //输出后缀
//                        echo $info->getFilename();  //输出文件名称
                          $data['thumb'] ='/uploads'.'/'.$info->getFilename();
                          //删除原来的缩略图
                          $art = Article::find($data->id);
                          if(file_exists($_SERVER['DOCUMENT_ROOT'].$art['thumb'])){
                              unlink($_SERVER['DOCUMENT_ROOT'].$art['thumb']);
                          }
                      }
                  }

              }

          });
          article::event('before_delete',function($data){
              dump($data);

              if($data['thumb']!==NULL){
                  //删除原来的缩略图
                  $art = Article::find($data->id);
                  if(file_exists($_SERVER['DOCUMENT_ROOT'].$art['thumb'])){
                      unlink($_SERVER['DOCUMENT_ROOT'].$art['thumb']);
                  }
              }

          });
      }
      public function add($data){
         if(empty($data)||!is_array($data)){
             return false;
         }

         $res = self::force()->save($data);
         if($res){
             return 1;
         }else{
             return 2;
         }
      }
      public function showArt(){
          $Articles = self::paginate(10);
          foreach($Articles as $Article){
            $Article->profile;
          }
          return $Articles;
      }
      public function edit($data){

          $res =  self::force()->save($data,['id'=>$data['id']]);
          return $res;
      }
}